<?php
	require_once('include/lsamp_curl.php');
	require_once('config.php');
	
	$db_conn = db_conn($db, $log_file);
	if($db_conn == false){
		exit;
	}
	$http_client = new lsamp_cURL(TRUE, 'cookies.txt', 'gzip', '', '', 30);
	
	for($i = 0; $i < count($login_accounts); $i ++){
		$ret = array(
			'Telephone_Number' => '',
			'Tipo_de_Saldo_1' => '',
			'Importe_1' => '',
			'Vigencia_1' => '',
			'Tipo_de_Saldo_2' => '',
			'Importe_2' => '',
			'Vigencia_2' => '',
			'Tipo_de_Saldo_3' => '',
			'Importe_3' => '',
			'Vigencia_3' => '',
			'Saldo_Total' => '',
			'Result' => 'Success'
		);
		fetch_data_by_tel($login_accounts[$i][0], $login_accounts[$i][1], $http_client, $ret, $log_file, $login_url, $scrape_url);	
		update_data_by_tel($ret, $db_conn, $db['table'], $log_file);
	}
	
	function fetch_data_by_tel($tel, $password, $http_client, &$ret, $log_file, $login_url, $scrape_url){
		error_log(date("d/m/y H:i:s") . " | " . "Start scraping data for tel: " . $tel . "\n",3,$log_file);
		$ret["Telephone_Number"] = $tel;
		$http_client->cookie('cookies.txt');
		$login_data = 'j_username=' . $tel
					. '&j_password=' . $password;
		$result = $http_client->post($login_url, $login_data, $errno, $error);	
		if($errno != 0){
			error_log(date("d/m/y H:i:s") . " | " . $tel . " | " . "Error: " . $error . "\n",3,$log_file);
			$ret["Result"] = "Failed";
		}else{
			error_log(date("d/m/y H:i:s") .  " | " . $tel . " | " ."Login information posted \n" , 3, $log_file);		
		}
		
		$result = $http_client->get($scrape_url, $errno, $error);
		if($errno != 0){
			error_log(date("d/m/y H:i:s") . " | " . $tel . " | " . "Error: " . $error . "\n",3,$log_file);
			$ret["Result"] = "Failed";		
		}else{
			error_log(date("d/m/y H:i:s") .  " | " . $tel . " | " ."Fetched page with required table \n" , 3, $log_file);		
		}
		
		// scrape data
		$result = str_replace("\r\n", "", $result);
		
		if(preg_match_all('#<td width="150" height="20" align="left">((?:.(?!/td>))+)#', $result, $matches)){
				if(preg_match('#<label class="contenidoNeg">((?:.(?!/label>))+)#',$matches[1][0], $match_tmp)){
				$ret["Tipo_de_Saldo_1"] = trim($match_tmp[1], "\t ");
			}else{
					error_log(date("d/m/y H:i:s") .  " | " . $tel . " | " ."The page's format changed \n" , 3, $log_file);
				$ret["Result"] = "Failed";
			}
			$ret["Importe_1"] = trim($matches[1][1], "\t ");
			$ret["Vigencia_1"] = trim($matches[1][2], "\t ");
			if(preg_match('#<label class="contenidoNeg">((?:.(?!/label>))+)#',$matches[1][3], $match_tmp)){			
				$ret["Tipo_de_Saldo_2"] = trim($match_tmp[1], "\t ");
			}else{
				error_log(date("d/m/y H:i:s") .  " | " . $tel . " | " ."The page's format changed \n" , 3, $log_file);
				$ret["Result"] = "Failed";
			}
			$ret["Importe_2"] = trim($matches[1][4], "\t ");
			$ret["Vigencia_2"] = trim($matches[1][5], "\t ");
			if(preg_match('#<label class="contenidoNeg">((?:.(?!/label>))+)#',$matches[1][6], $match_tmp)){
				$ret["Tipo_de_Saldo_3"] = trim($match_tmp[1], "\t ");
			}else{
				error_log(date("d/m/y H:i:s") .  " | " . $tel . " | " ."The page's format changed \n" , 3, $log_file);
				$ret["Result"] = "Failed";
			}
			$ret["Importe_3"] = trim($matches[1][7], "\t ");
			$ret["Vigencia_3"] = trim($matches[1][8], "\t ");
			$ret["Saldo_Total"] = 0;
			for($i = 1; $i < 4; $i++){
				$ret["Saldo_Total"] += substr($ret['Importe_' . $i], 1, strlen($ret["Importe_". $i]));
			}		 
			$ret["Saldo_Total"] = '$' . number_format($ret["Saldo_Total"], 2, '.', '');
		}else{
			error_log(date("d/m/y H:i:s") .  " | " . $tel . " | " ."The page's format changed \n" , 3, $log_file);
			$ret["Result"] = "Failed";
		}
		error_log(date("d/m/y H:i:s") . " | " . "Stop scraping data for tel: " . $tel . "\n",3,$log_file);
	}
	
	function update_data_by_tel($ret, $db_conn, $db_table, $log_file){
		$select = 'SELECT Telephone_Number FROM' . ' ' . $db_table
					. " WHERE Telephone_Number = '" . $ret["Telephone_Number"] . "'";
		$s_ret = mysql_query($select, $db_conn);
		if(mysql_num_rows($s_ret) == 0){	
			$insert = 'INSERT INTO ' . $db_table . "(
						`Telephone_Number` ,
						`Tipo_de_Saldo_1` ,
						`Importe_1` ,
						`Vigencia_1` ,
						`Tipo_de_Saldo_2` ,
						`Importe_2` ,
						`Vigencia_2` ,
						`Tipo_de_Saldo_3` ,
						`Importe_3` ,
						`Vigencia_3` ,
						`Saldo_Total` ,
						`Result`
						) VALUE (";
			$insert .= "'" . $ret['Telephone_Number'] . "'," 
						. "'" . $ret['Tipo_de_Saldo_1'] . "',"
						. "'" . $ret['Importe_1'] . "',"
						. "'" . $ret['Vigencia_1'] . "',"
						. "'" . $ret['Tipo_de_Saldo_2'] . "',"
						. "'" . $ret['Importe_2'] . "',"
						. "'" . $ret['Vigencia_2'] . "',"
						. "'" . $ret['Tipo_de_Saldo_3'] . "',"
						. "'" . $ret['Importe_3'] . "',"
						. "'" . $ret['Vigencia_3'] . "',"
						. "'" . $ret['Saldo_Total'] . "',"
						. "'" . $ret['Result'] . "'"
						. ")";
			$i_rt = mysql_query($insert, $db_conn);
			if(!$i_rt){
				error_log(date('d/m/y H:i:s') . " | " . $ret['Telephone_Number'] . " | Could not insert the data into the database | " . $insert . " | " . mysql_error($db_conn) . "\n", 3, $log_file);
			}else{
				error_log(date('d/m/y H:i:s') .  " | " . $ret['Telephone_Number'] . " | Inserted the data in database \n", 3, $log_file);
			}
		}else{
			$update = 'UPDATE ' . $db_table	. ' SET'
						. " `Tipo_de_Saldo_1`='" . $ret["Tipo_de_Saldo_1"] . "',"
						. " `Importe_1`='" . $ret["Importe_1"] . "',"
						. " `Vigencia_1`='" . $ret["Vigencia_1"] . "',"
						. " `Tipo_de_Saldo_2`='" . $ret["Tipo_de_Saldo_2"] . "',"
						. " `Importe_2`='" . $ret["Importe_2"] . "',"
						. " `Vigencia_2`='" . $ret["Vigencia_2"] . "',"
						. " `Tipo_de_Saldo_3`='" . $ret["Tipo_de_Saldo_3"] . "',"
						. " `Importe_3`='" . $ret["Importe_3"] . "',"
						. " `Vigencia_3`='" . $ret["Vigencia_3"] . "',"
						. " `Saldo_Total`= '" . $ret["Saldo_Total"] . "', "
						. " `Result`='" . $ret["Result"]. "'"
						. " WHERE `Telephone_Number`='" . $ret["Telephone_Number"] . "'";
			$u_rt = mysql_query($update, $db_conn);
			if(!$u_rt){
				error_log(date('d/m/y H:i:s') . " | " . $ret['Telephone_Number'] . " | Could not update the data in the database | " . $update . " | " . mysql_error($db_conn) . "\n", 3, $log_file);
			}else{
				error_log(date('d/m/y H:i:s') .  " | " . $ret['Telephone_Number'] . " | Updated the data in database | \n", 3, $log_file);
			}
		}
					
	}
	
	function db_conn($db, $log_file){
		// connect to source database
		$db_conn = mysql_connect($db["host"], $db["username"], $db["password"]);
		if(!$db_conn || !mysql_select_db($db["name"], $db_conn)){
			error_log(date('d/m/y H:i:s') . " | Could not connect to source database, or the database name is incorrect \n", 3, $log_file);
			return false;			
		}
		return $db_conn;
	}
?>